from itsdangerous import TimedJSONWebSignatureSerializer
from comment.utils.const import SECRET_KEY,JWT_EXPIRY_SECOND
from flask import current_app
from comment.models.user import User
import jwt
from datetime import datetime,timedelta
from jwt import PyJWTError
def generate_tokens(uid):
    '''
    根据已经登录的用户id生成token
    :param uid:登录后的用户id
    :return:
    '''
    playload={
        'id':uid,
        'exp':datetime.utcnow()+timedelta(seconds=JWT_EXPIRY_SECOND)
    }
    #需要传3个参数，参数一：playload是一个字典，加密的用户id和有效时间，参数二：密钥，参数三：算法名字
    s = jwt.encode(playload=playload,secret_key=SECRET_K,algorithm='HS256')
    #生成token
    return s
def verify_token(token_str):
    '''
    验证token，验证成功后，返回用户id
    :param token_str:要验证的token
    :return:
    '''
    try:
        data = jwt.decode(token_str,key=SECRET_KEY,algorithms='HS256')#实质上是一个解密的过程
        current_app.logger.info(data)

        #data = jwt.decode(token_str, key=const.SECRET_KEY, algorithms='HS256')
    except PyJWTError as e:
        current_app.logger.info('token验证失败')
        return {'message':'token验证失败'}
    #如果token验证成功，.还需要看当前用户状态是否正常
    user =User.query.filter(User.id==data['id']).first()
    if user and user.status !=0:
        return {'message':'数据库中的用户状态过期'}
    return {'id':user.id}